<?php

namespace app\api\controller;

use app\api\model\ConfigSystem as Config;
use app\api\model\TopupSelect;
use app\api\model\Privatechat;
use app\api\model\Topup as TopupModel;
use app\service\UserIntimate;
use think\Db;

class Topup extends Common
{
    public function lists()
    {
        $data = TopupSelect::all(function($query){
            $query->field('is_hidden, sort, create_time, update_time', true)->where(['is_hidden' => 0, 'channel_sex'=>$this->member['sex'] == '女' ? 1 : 2])->order('sort desc');
        });

        $result = Db::name('topup')->where(['fk_userid' => $this->member['id'], 'state' => 1])->find();
        $nobles = Db::name('grade_noble')->column('id, name, icon');
        $cars = Db::name('car')->column('id, name, cover');

        foreach ($data as $key => $item) {
            if (!$result && $item['first_price'] > 0) {
                $data[$key]['price'] = $item['first_price'];
                $data[$key]['is_first'] = 1;
            } else {
                $data[$key]['is_first'] = 0;
            }

            $data[$key]['price'] = (int)sprintf("%.0f", $item['price']);
            $data[$key]['money'] = (int)sprintf("%.0f", $item['money']);
            $data[$key]['reward_money'] = (int)sprintf("%.0f", $item['reward_money']);

            if ($item['reward_noble_day'] && $item['reward_noble'] && isset($nobles[$item['reward_noble']])) {
                $data[$key]['reward_noble_name'] = $nobles[$item['reward_noble']]['name'];

                $data[$key]['reward_noble_cover'] = changeUrl($nobles[$item['reward_noble']]['icon']);
            }

            if ($item['reward_car_day'] && $item['reward_car'] && isset($cars[$item['reward_car']])) {
                $data[$key]['reward_car_name'] = $cars[$item['reward_car']]['name'];

                $data[$key]['reward_car_cover'] = changeUrl($cars[$item['reward_car']]['cover']);
            }

            unset($data[$key]['first_price']);
        }

        return $this->pass($data);
    }

    public function recharge()
    {
        $params = getRsaPostParamArr();
    
        if (isset($params['paymethod']) && in_array($params['paymethod'], [0,1,2])) {
            if (!isset($params['userid']) || !$params['userid']) {
                return $this->miss('操作失败');
            }

            $params['userid'] = intval($params['userid']);

            // $params['paymethod']=1;
            // $params['id'] = 17;

            $actionText = $params['paymethod'] ? '支付宝' : '微信';

            $user = Db::name('user')->where(['id' => $params['userid'], 'reg'=>1])->field('id,register_datetime')->find();
            if (!$user) {
                return $this->miss('操作失败');
            }

            $config = Config::index('topup');

            $topup = TopupSelect::get($params['id']);

            if (!$topup) return $this->return['common.error.notExist'];

            if ($this->member['sex'] == '女') {
                if ($topup['channel_sex'] != 1) {
                    return $this->return['common.error.notExist'];
                }
            } else if ($topup['channel_sex'] != 2) {
                return $this->return['common.error.notExist'];
            }

            $rechargecount = Db::name('user_data')->where(['user_id' => $this->member['id']])->value('topup');
            $rechargecount = $rechargecount ?? 0;
            $uid = $params['userid'];
            // $uids = _getAllUser($uid);

            $userTempQuota = Db::name('topup_temporary_quota')->where(['user_id'=>$uid, 'quota'=>['>', 0]])->whereTime('time', 'today')->value('quota');
            $userTempQuota = $userTempQuota ? $userTempQuota : 0;

            $total = Db::name('topup')->master()->where(['fk_userid' => $uid, 'state' => 1])->whereTime('addtime', 'd')->sum('price');
            // $total = Db::name('topup')->where(['fk_userid' => $uid, 'state' => 1])->whereTime('addtime', 'd')->sum('price');

            $config_for_rate = Config::index('', 'rate');


            $topup_config = $topup['money'] / $topup['price'];

            // if ($topup_config > $config_for_rate['rate']) {
            //     return $this->miss('充值套餐出错');
            // }


            // 危险标签里的充值限制
            $user_others = Db::name('user_repeat_check')->where(['user_id'=>$uid])->value('device_ids');
            if ($user_others) {
                $otheruids = [];
                $devices = explode(',', $user_others);
                foreach ($devices as $device) {
                    $uids = Db::name('user_repeat_check')->where('find_in_set("'.$device.'",device_ids)')->cache(600)->fetchSql(false)->column('user_id');
                    $otheruids = array_merge($otheruids, $uids);
                }
                if (sizeof($otheruids)) {
                    $dangeruids = Db::name('user')->where(['id'=>['in', $otheruids]])->where('find_in_set(5, danger_tags)')->column('id');
                    if (sizeof($dangeruids)) {
                        $topupmin = Db::name('topup_limit')->where(['user_id'=>['in', $dangeruids]])->order('value asc')->value('value');
                        if ($topupmin > 0 && $topupmin + $userTempQuota < $total + $topup['price']) {
                            Db::name('topup_user_limit_records')->insert(['user_id'=>$uid, 'price'=>$topup['price'], 'limit'=>$topupmin + $userTempQuota, 'time'=>time()]);
                            //return $this->miss('由于本公司是小微企业，' . $actionText . '支付今日已经限额，请改日再充');
                            return $this->miss('支付今日已经限额，请改日再充');
                        }
                    }
                }
            }


            $userlimit = Db::name('topup_limit')->where(['user_id'=>$params['userid'], 'value'=>['>', 0]])->value('value');
            // $rechargecount = Db::name('topup')->where(['fk_userid'=>['in', $uids], 'state'=>1])->fetchSql(false)->sum('price');
            // $rechargecount = Db::name('topup')->where(['fk_userid'=>$uid, 'state'=>1])->fetchSql(false)->sum('price');
            // $rechargecount = Db::name('user_data')->where(['user_id'=>$uid])->value('topup');
            // $rechargeInit = UserIntimate::TopupCount($uid);
            // $rechargecount = $rechargeInit['topup'] ?? 0;
            // $userids = $rechargeInit['userids'];



            $limitdate = '2023-04-15 00:00:00';
            $limittime = strtotime($limitdate);

            // $hasminreguid = Db::name('user')->where(['id'=>['in', $userids],'register_datetime'=>['<=', $limitdate]])->count();
            // if ($hasminreguid) {
            //     return $this->miss('该公司未提供收款金融资质，已暂停合作');
            // }

            // if (strtotime($user['register_datetime']) < $limittime) {
            //     return $this->miss('该公司未提供收款金融资质，已暂停合作');
            // } else {
            //     return $this->miss('由于本公司是小微企业，' . $actionText . '支付今日已经限额，请改日再充');
            // }
            if($userlimit){
                if($total + $topup['price'] > $userlimit + $userTempQuota){
                    Db::name('topup_user_limit_records')->insert(['user_id'=>$uid, 'price'=>$topup['price'], 'limit'=>$userlimit + $userTempQuota, 'time'=>time()]);
                    //return $this->miss('由于本公司是小微企业，' . $actionText . '支付今日已经限额，请改日再充');
                    return $this->miss('支付今日已经限额，请改日再充');
                }
            }else if($total + $topup['price'] > 20){
                $rechargeLimitTempUp = $this->rechargeLimitTempUp($rechargecount,$userTempQuota,$total,$config['topup_max'],$topup['price']);
                if (!$rechargeLimitTempUp) {
                    //return $this->miss('由于本公司是小微企业，' . $actionText . '支付今日已经限额，请改日再充');
                    return $this->miss('支付今日已经限额，请改日再充');
                }
            }


            // if($rechargecount + $topup['price'] >= 10000){
            //     $user = Db::name('user')->where(['id'=>$params['userid']])->find();
            //     if($user['yqr']){
            //         $parent = Db::name('user')->where(['yqm'=>$user['yqr']])->value('id');
            //         if($parent){
            //             Privatechat::notice($parent, '禁止让对方充值比较高还在解锁，排查发现会冻结积分，' . $user['name'] . '（'.$user['id'].'），本平台严谨欺骗，涉黄。' );
            //         }
            //     }
            // }


            $result = Db::name('topup')->where(['fk_userid' => $params['userid'], 'state' => 1])->find();

            if (!$result && $topup['first_price'] > 0) {
                $price = $topup->first_price;
            } else {
                $price = $topup->price;
            }

            $money = $topup->money;

    
            $price = round($price, 2);
            $params['coupon_id'] = isset($params['coupon_id']) ? $params['coupon_id'] : 0;
            $order = TopupModel::index($params['userid'], $price, $money, $params['paymethod'], $params['id'], $params['coupon_id']);
    // $params['h5'] =0;
            if (isset($params['h5']) && $params['h5']) {
                //$action = 'api/Alipaywap/tradeAppPay';
                return $this->pass(['order_sn' => $order['order_sn'], 'url' => 'api/wap/pay']);
            } else {
                if ($params['paymethod']) {
                    $action = 'api/Alipay/tradeAppPay';
                    $action = 'api/Adapay/index';
                    $trade_type = 'alipay';
                } else {
                    $action = 'api/Wechat/app';
                    if (isset($params['w2'])) {
                        $action = 'api/Wechat2/app';
                    }
                    // $action = 'api/juhepay/index';
                    $trade_type = 'T_NATIVE';
                }
            }
            
            return action($action, ['order_sn' => $order['order_sn'], 'total_amount' => $order['price'], 'trade_type'=>$trade_type]);
            return action($action, ['order_sn' => $order['order_sn'], 'total_amount' => $order['price']]);
        }
    }
    public function rechargehf()
    {
        $params = getRsaPostParamArr();

        if (isset($params['paymethod']) && in_array($params['paymethod'], [0,1,2])) {
            if (!isset($params['userid']) || !$params['userid']) {
                return $this->miss('操作失败');
            }

            $params['userid'] = intval($params['userid']);

            // $params['paymethod']=1;
            // $params['id'] = 17;

            $actionText = $params['paymethod'] ? '支付宝' : '微信';

            $user = Db::name('user')->where(['id' => $params['userid'], 'reg'=>1])->field('id,register_datetime')->find();
            if (!$user) {
                return $this->miss('操作失败');
            }

            $config = Config::index('topup');

            $topup = TopupSelect::get($params['id']);


            if (!$topup) return $this->return['common.error.notExist'];

            if ($this->member['sex'] == '女') {
                if ($topup['channel_sex'] != 1) {
                    return $this->return['common.error.notExist'];
                }
            } else if ($topup['channel_sex'] != 2) {
                return $this->return['common.error.notExist'];
            }

            $rechargecount = Db::name('user_data')->where(['user_id' => $this->member['id']])->value('topup');
            $rechargecount = $rechargecount ?? 0;
            $uid = $params['userid'];
            // $uids = _getAllUser($uid);

            $userTempQuota = Db::name('topup_temporary_quota')->where(['user_id'=>$uid, 'quota'=>['>', 0]])->whereTime('time', 'today')->value('quota');
            $userTempQuota = $userTempQuota ? $userTempQuota : 0;

            $total = Db::name('topup')->master()->where(['fk_userid' => $uid, 'state' => 1])->whereTime('addtime', 'd')->sum('price');
            // $total = Db::name('topup')->where(['fk_userid' => $uid, 'state' => 1])->whereTime('addtime', 'd')->sum('price');

            $config_for_rate = Config::index('', 'rate');


            $topup_config = $topup['money'] / $topup['price'];

            // if ($topup_config > $config_for_rate['rate']) {
            //     return $this->miss('充值套餐出错');
            // }


            // 危险标签里的充值限制
            $user_others = Db::name('user_repeat_check')->where(['user_id'=>$uid])->value('device_ids');
            if ($user_others) {
                $otheruids = [];
                $devices = explode(',', $user_others);
                foreach ($devices as $device) {
                    $uids = Db::name('user_repeat_check')->where('find_in_set("'.$device.'",device_ids)')->cache(600)->fetchSql(false)->column('user_id');
                    $otheruids = array_merge($otheruids, $uids);
                }
                if (sizeof($otheruids)) {
                    $dangeruids = Db::name('user')->where(['id'=>['in', $otheruids]])->where('find_in_set(5, danger_tags)')->column('id');
                    if (sizeof($dangeruids)) {
                        $topupmin = Db::name('topup_limit')->where(['user_id'=>['in', $dangeruids]])->order('value asc')->value('value');
                        if ($topupmin > 0 && $topupmin + $userTempQuota < $total + $topup['price']) {
                            Db::name('topup_user_limit_records')->insert(['user_id'=>$uid, 'price'=>$topup['price'], 'limit'=>$topupmin + $userTempQuota, 'time'=>time()]);
                            //return $this->miss('由于本公司是小微企业，' . $actionText . '支付今日已经限额，请改日再充');
                            return $this->miss('支付今日已经限额，请改日再充');
                        }
                    }
                }
            }


            $userlimit = Db::name('topup_limit')->where(['user_id'=>$params['userid'], 'value'=>['>', 0]])->value('value');
            // $rechargecount = Db::name('topup')->where(['fk_userid'=>['in', $uids], 'state'=>1])->fetchSql(false)->sum('price');
            // $rechargecount = Db::name('topup')->where(['fk_userid'=>$uid, 'state'=>1])->fetchSql(false)->sum('price');
            // $rechargecount = Db::name('user_data')->where(['user_id'=>$uid])->value('topup');
            // $rechargeInit = UserIntimate::TopupCount($uid);
            // $rechargecount = $rechargeInit['topup'] ?? 0;
            // $userids = $rechargeInit['userids'];



            $limitdate = '2023-04-15 00:00:00';
            $limittime = strtotime($limitdate);

            // $hasminreguid = Db::name('user')->where(['id'=>['in', $userids],'register_datetime'=>['<=', $limitdate]])->count();
            // if ($hasminreguid) {
            //     return $this->miss('该公司未提供收款金融资质，已暂停合作');
            // }

            // if (strtotime($user['register_datetime']) < $limittime) {
            //     return $this->miss('该公司未提供收款金融资质，已暂停合作');
            // } else {
            //     return $this->miss('由于本公司是小微企业，' . $actionText . '支付今日已经限额，请改日再充');
            // }
            if($userlimit){
                if($total + $topup['price'] > $userlimit + $userTempQuota){
                    Db::name('topup_user_limit_records')->insert(['user_id'=>$uid, 'price'=>$topup['price'], 'limit'=>$userlimit + $userTempQuota, 'time'=>time()]);
                    //return $this->miss('由于本公司是小微企业，' . $actionText . '支付今日已经限额，请改日再充');
                    return $this->miss('支付今日已经限额，请改日再充');
                }
            }else if($total + $topup['price'] > 20){
                $rechargeLimitTempUp = $this->rechargeLimitTempUp($rechargecount,$userTempQuota,$total,$config['topup_max'],$topup['price']);
                if (!$rechargeLimitTempUp) {
                    //return $this->miss('由于本公司是小微企业，' . $actionText . '支付今日已经限额，请改日再充');
                    return $this->miss('支付今日已经限额，请改日再充');
                }
            }


            // if($rechargecount + $topup['price'] >= 10000){
            //     $user = Db::name('user')->where(['id'=>$params['userid']])->find();
            //     if($user['yqr']){
            //         $parent = Db::name('user')->where(['yqm'=>$user['yqr']])->value('id');
            //         if($parent){
            //             Privatechat::notice($parent, '禁止让对方充值比较高还在解锁，排查发现会冻结积分，' . $user['name'] . '（'.$user['id'].'），本平台严谨欺骗，涉黄。' );
            //         }
            //     }
            // }


            $result = Db::name('topup')->where(['fk_userid' => $params['userid'], 'state' => 1])->find();

            if (!$result && $topup['first_price'] > 0) {
                $price = $topup->first_price;
            } else {
                $price = $topup->price;
            }

            $money = $topup->money;

            $price = round($price, 2);
            $params['coupon_id'] = isset($params['coupon_id']) ? $params['coupon_id'] : 0;
            $price=0.01;//测试支付
            $order = TopupModel::index($params['userid'], $price, $money, $params['paymethod'], $params['id'], $params['coupon_id']);

            $action = 'api/adapay/hfwxmini';
            //echo $order['order_sn'];die;
            return action($action, ['order_sn' => $order['order_sn'], 'total_amount' => $order['price']]);
        }
    }
    public function rechargeLimitTempUp($rechargecount,$userTempQuota,$total,$topup_max,$topup_price, $record = true)
    {
        return true;
        $rechargeStatus = false;
        $userlimit = 0;
        if($rechargecount >= 30000){
            $userlimit = 20 + $userTempQuota;
        } else if($rechargecount >= 27000){
            $userlimit = 40 + $userTempQuota;
        } else if($rechargecount >= 23000){
            $userlimit = 60 + $userTempQuota;
        } else if($rechargecount >= 20000){
            $userlimit = 80 + $userTempQuota;
        } else if($rechargecount >= 15000){
            $userlimit = 100 + $userTempQuota;
        } else if($rechargecount >= 10000){
            $userlimit = 200 + $userTempQuota;
        } else if($rechargecount >= 5000){
            $userlimit = 400 + $userTempQuota;
        } else {
            $userlimit = $topup_max + $userTempQuota;
        }
        $rechargeStatus = $total + $topup_price <= $userlimit;

        if (!$rechargeStatus) {
            if ($record) {
                Db::name('topup_user_limit_records')->insert(['user_id'=>$this->member['id'], 'price'=>$topup_price, 'limit'=>$userlimit + $userTempQuota, 'time'=>time()]);
            }
            if($rechargecount >= 30000){
                if ($total != 20) return false;
            } else if($rechargecount >= 27000){
                if ($total != 40) return false;
            } else if($rechargecount >= 23000){
                if ($total != 60) return false;
            } else if($rechargecount >= 20000){
                if ($total != 80) return false;
            } else if($rechargecount >= 15000){
                if ($total != 100) return false;
            } else if($rechargecount >= 10000){
                if ($total != 200) return false;
            } else if($rechargecount >= 5000){
                if ($total != 400) return false;
            } else if ($total != $topup_max) {
                return false;
            }
            if ($this->member['volley'] >= 3) return false;
            if ($rechargecount >= 25000) return false;
            if ($userTempQuota > 0) return false;

            $userTempQuota = 0;
            if($rechargecount < 3000){
                $userTempQuota = 50;
            } else if($rechargecount < 5000){
                $userTempQuota = 30;
            } else if($rechargecount < 10000){
                $userTempQuota = 20;
            } else if($rechargecount < 20000){
                $userTempQuota = 10;
            } else {
                return false;
            }

            Db::name('topup_temporary_quota')->insert([
                'user_id'=>$this->member['id'],
                'quota'=>$userTempQuota,
                'time'=>time()
            ]);
            return $this->rechargeLimitTempUp($rechargecount,$userTempQuota,$total,$topup_max,$topup_price, false);
        }

        return $rechargeStatus;

    }
    public function rechargeweb()
    {
        $post = input('post.');
        $user = Db::name('user')->where(['phone'=>$post['phone']])->find();
            if (!$user) {
                return $this->miss('账号未注册，请先下载APP注册');
            }

            $uid = intval($user['id']);

            $config = Config::index('topup');

            $total = Db::name('topup')->where(['fk_userid' => $uid, 'state' => 1])->whereTime('addtime', 'd')->sum('price');
            if ($total >= $config['topup_max']) {
                return $this->miss($actionText . '充值已被限额，请改日再充');
            }

            $config_for_rate = Config::index('', 'rate');

            $topup = TopupSelect::get($post['id']);

            if (!$topup) return $this->return['common.error.notExist'];

            $topup_config = $topup['money'] / $topup['price'];

            if ($topup_config > $config_for_rate['rate']) {
                return $this->miss('充值套餐出错');
            }

            $userlimit = Db::name('topup_limit')->where(['user_id'=>$uid, 'value'=>['>', 0]])->value('value');
            $rechargecount = Db::name('topup')->where(['fk_userid'=>$uid, 'state'=>1])->fetchSql(false)->sum('price');
            if($userlimit){
                if($total + $topup['price'] > $userlimit){
                    return $this->miss('支付今日已经限额，请改日再充');
                }
            }else if($total + $topup['price'] >= 100){
                if($rechargecount >= 25000){
                    return $this->miss('支付今日已经限额，请改日再充');
                }
                if($rechargecount >= 15000 && $total + $topup['price'] >= 300){
                    return $this->miss('支付今日已经限额，请改日再充');
                }
                if($rechargecount >= 10000 && $total + $topup['price'] >= 600){
                    return $this->miss('支付今日已经限额，请改日再充');
                }
                if($rechargecount >= 5000 && $total + $topup['price'] >= 1000){
                    return $this->miss('支付今日已经限额，请改日再充');
                }
            }
            $result = Db::name('topup')->where(['fk_userid' => $uid, 'state' => 1])->find();
            if (!$result && $topup['first_price'] > 0) {
                $price = $topup->first_price;
            } else {
                $price = $topup->price;
            }
            $money = $topup->money;
            $price = round($price, 2);
            $order = TopupModel::index($uid, $price, $money, 1, $post['id']);
            return $this->pass(['order_sn' => $order['order_sn'], 'url' => 'api/wap/pay']);
    }
}
